<!--
*@Author: QWP
*@Description: 高拍仪
*@Date: 2023-08-30 16:20:34
-->
<template>
  <!-- <u-dialog title="高拍仪" -->
  <u-dialog title="附件上传"
    confirmText="上传"
    v-bind="$attrs"
    
    :showFull="false"
    :fullscreen="true"
    :loading="loading"
    ref="upload"
    @submit="submit"
    @close="clear"
    custom-class="u-upload-dialog">
    <div class="f-flex-column f-h-100" style="align-items: center">
      <div id="showArea" style="height: calc(100% - 100px); min-width: 400px">
        <img id="view1" src="http://127.0.0.1:38088/video=stream&camidx=0" alt="暂未获取到主摄像头信息"
          style="width: 100%; height: 100%">
      </div>
      <div class="f-flex-row" style="height: 100px; flex-wrap: wrap;">
        <div v-for="(item, index) in fileList"
          :key="item"
          style="margin-right: 10px"
          class="f-flex-column">
          <a-image
            style="width: 100px; height: 80px;"
            :src="item"
            fit="contain" 
            :preview="false"
            @click.stop="showImgView(index)"/>
            <u-input v-model="finalFiles[index]['name']" style="width: 100px" />
        </div>
        <a-image fit="contain" 
          ref="viewImg"
          :preview="false"
          :preview-src-list="viewList"
          :initial-index="imgIndex"
          @click.stop="clickImg"
          v-show="false"
          />
      </div>
    </div>
    <template slot="footer">
      <u-icon-button @click="open_view1" icon="el-icon-picture-outline">打开主摄像头视频</u-icon-button>
      <u-icon-button @click="close_view1" icon="el-icon-circle-close">关闭主摄像头视频</u-icon-button>
      <u-icon-button @click="view1_scan" icon="el-icon-camera">主摄像头拍照</u-icon-button>
      <!-- <u-icon-button @click="open_auto_scan" icon="el-icon-camera">开启自动拍照</u-icon-button> -->
      <!-- <u-icon-button @click="close_auto_scan" icon="el-icon-camera">关闭自动拍照</u-icon-button> -->
      <!-- <u-icon-button @click="rotate(90)" icon="el-icon-refresh-left">左转</u-icon-button> -->
      <!-- <u-icon-button @click="rotate(270)" icon="el-icon-refresh-right">右转</u-icon-button> -->
    </template>
  </u-dialog>
</template>
<script>
// import fileService from '@/service/common/file.service.js'
// import enumService from '@/service/common/enmu.service.js'
import axios from 'axios'
// import html2canvas from 'html2canvas'
import { jsonCopy, messageC, urlFile } from '@/util/common'
export default {
  name: 'u-high-camera',
  props: {
    bizType: { type: String, default: ''},
    params: {
      type: Object,
      default: () => {}
    },
    // 是否多传
    multiple: { type: Boolean, default: true }
  },
  data () {
    return {
      imgIndex: 0,
      // 小图预览
      fileList: [
        // urlFile('finance/welcome.png'),
        // urlFile('datacenter/main.jpg')
      ],
      // 大图预览数据
      viewList: [],
      // 最终保存数据
      finalFiles: [
        // {name: 'aaa'},
        // {name: 'bbb'},
      ],

      wrapperElem: null,

      loading: false,
       
      api: "http://127.0.0.1:38088"
    }
  },
  mounted() {
  },
  methods: {
    // 初始化摄像头
    initCamera() {
      this.$nextTick(() => {
        let showArea = document.getElementById("showArea");
        if(showArea) {
          showArea.style.width = (showArea.clientHeight) * 0.72 + 'px'
        }
      })
      // 加载主摄像头视频模式
      let view1_mode_data1 = { "camidx": "0", "mode": "0" };
      let view1_mode_data2 = { "camidx": "0", "mode": "1" };
      this.xhrFun("http://127.0.0.1:38088/device=getresolution", view1_mode_data2)
        .then((res)=>{
          if(res.data.data.split("|").length > 1){
            let data = new Object()
            data.key = '0'
            data.value = 'YUY2'
          }
        })
      this.xhrFun(this.api + "/device=getresolution", view1_mode_data1)
        .then((res)=>{
        if(res.data.data.split("|").length > 1){
          let data = new Object()
          data.key = '1'
          data.value = 'MJPG'
        }
      })
    },

    // 打开主摄像头
    open_view1 () {
      document.getElementById('view1').src = this.api + '/video=stream&camidx=0?1'
    },

    // 关闭主摄像头
    close_view1 () {
      let data = {"camidx": "0"}
      this.xhrFun(this.api + "/video=close?", data)
        .then(()=>{
          document.getElementById('view1').src = ''
        })
    },

    // 旋转
    rotate (angle) {
      let data = {"camidx": '0', "rotate": String(angle)}
      this.xhrFun(this.api + "/video=rotate?", data)
        .then((res)=>{
        })
    },

    // 兼容atob 的使用
    jrTtob() {
      if(!window.atob) {
        window.atob = function(encodedString) {
          var base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
          var decodedString = '';
          var currentChar, charCode1, charCode2, charCode3, encIndex1, encIndex2, encIndex3, encIndex4;

          for (var i = 0; i < encodedString.length; i += 4) {
            encIndex1 = base64Chars.indexOf(encodedString[i]);
            encIndex2 = base64Chars.indexOf(encodedString[i + 1]);
            encIndex3 = base64Chars.indexOf(encodedString[i + 2]);
            encIndex4 = base64Chars.indexOf(encodedString[i + 3]);

            charCode1 = (encIndex1 << 2) | (encIndex2 >> 4);
            charCode2 = ((encIndex2 & 15) << 4) | (encIndex3 >> 2);
            charCode3 = ((encIndex3 & 3) << 6) | encIndex4;

            decodedString += String.fromCharCode(charCode1);

            if (encIndex3 !== 64) {
              decodedString += String.fromCharCode(charCode2);
            }
            if (encIndex4 !== 64) {
              decodedString += String.fromCharCode(charCode3);
            }
          }

          return decodedString;
        }
      }
    },

    // base64 转文件
    base64ToFile(base64Data, index = -1) {
      this.jrTtob();
      let currentData = jsonCopy(this.finalFiles)[index]
      var arr = base64Data.split(','),
        bstr = window.atob(arr[0]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let filename = index == -1 ? `${'单据' + (this.finalFiles.length + 1)}.jpg` : currentData.name;
      let file = new File([u8arr], `${filename}`, {
        type: 'image/png',
      })

      file.uid = Date.parse(new Date())
      // 直接添加文件
      if(index == -1) {
        const tempData = {
          name: filename,
          percentage: 0,
          raw: file,
          size: file.size,
          status: "ready",
          uid: file.uid
        }
        this.finalFiles.push(tempData)
      }
      // 修改单个文件
      else {
        currentData.raw = file;
        currentData.size = file.size;
        currentData.uid = file.uid;
        this.finalFiles.splice(index, 1, currentData)
      }
    },

    // 自定义请求
    xhrFun(url, data) {
      return new Promise((resolve, reject) => {
        let params = [];
        for(let key in data) {
          params.push(`${key}=${data[key]}`)
        }
        var xhr = new XMLHttpRequest(); 
        xhr.open ("GET", url + params.join('&'),  true);
        xhr.send(null);  //发送请求
        xhr.onreadystatechange = function() {
          if(xhr.readyState == 4) {
            resolve({
              data: JSON.parse(xhr.response)
            })
          }
        }
      })
    },

    // 主头拍照
    view1_scan () {
      let data = {
        "filepath": "base64",
        "rotate": "0",
        "cutpage": "0",
        "camidx": "0",
        "ColorMode": "0",
        "quality": "3"
      }
      
      this.xhrFun(this.api + "/video=grabimage?", data)
        .then((res) => {
          this.fileList.push("data:image/jpg;base64," +res.data.photoBase64)
          this.base64ToFile(res.data.photoBase64)
        })
    },

    // 展平拍照
    flat_scan () {
      let data = {
        "filepath": "",
        "rotate": "0",
        "camidx": "0",
        "cutpage": "0",
        "autoflat": {
          "flat": "1",
          "leftfilepath": "D://left.jpg",
          "rightfilepath": "D://right.jpg",
          "removefinger": "1",
          "doublepage": "1"
        }
      }

      this.xhrFun(this.api + "/video=autoflat?", data)
        .then((res)=>{
          // this.add_image(res.data.photoBase64)
          // this.add_image(res.data.leftphotoBase64)
          // this.add_image(res.data.rightphotoBase64)
        })
    },

    // 开启自动拍照
    open_auto_scan() {
      let data = {
        "movedetecflag": "1",
        "listpath": "D://a",
        "filepath": "hy"
      }
      this.xhrFun(this.api + "/video=movedetec?", data)
        .then(()=>{
          this.fileList.push("data:image/jpg;base64," +res.data.data)
          this.base64ToFile(res.data.data)
        })
    },

    // 关闭自动拍照
    close_auto_scan () {
      let data = {"movedetecflag": "0"}
      this.xhrFun(this.api + "/video=movedetec?", data)
        .then(()=>{
        })
    },

    // 提交
    submit() {
      if(this.finalFiles.length == 0) {
        this.$common.alertC("请先选择要上传的文件!", "warning");
        return
      }

      this.loading = true;
      for(let i = 0; i < this.finalFiles.length; i++) {
        const file = this.finalFiles[i];
        let form = new FormData();
        form.append('storagetype', 'LOCAL')
        form.append('file', file.raw)
        form.append('bucket', this.$common.nullC(this.params['bucket']))
        form.append('biztype', this.$common.nullC(this.params['biztype']))
  
        fileService.upload(form).then(res => {
          if(res.data.code == 0) {
            this.uploadNum += 1;
            this.$emit('success', { ...res.data.data, originalfilename: file.name }, i == this.finalFiles.length - 1)
            if(i == this.finalFiles.length - 1) {
              this.loading = false;
              this.$common.alertC(res.data.msg, "success")
              this.clear();
            }
          }
          else {
            this.loading = false;
            this.$common.alertC(res.data.msg, 'warning')
          }
        })
        .catch(err => {
          this.loading = false;
          if(err['data']) {
            this.$common.alertC(err.data.msg, "error")
          }
        })
      }
    },

    // 清除文件
    clear() {
      setTimeout(() => {
        this.fileList.splice(0, this.fileList.length);
        this.viewList.splice(0, this.viewList.length);
        this.finalFiles.splice(0, this.finalFiles.length);
      }, 100)
    },

    // 显示大图预览
    showImgView(index) {
      this.imgIndex = index;
      this.viewList.splice(0, this.fileList.length, ...this.fileList)
      this.$refs.viewImg.clickHandler()
      this.clickImg()
    },

    clickImg(idx) {
      this.$nextTick(()  => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        )
        let downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-check");
        wrapper[0].appendChild(downImg);

        if(wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.wrapperElem.addEventListener("click", this.hideCusBtn);
        }
      })
    },

    // 点击事件
    hideCusBtn(e) {
      let className = e.target.className;
      const _this = this;
      // 点击保存按钮
      if (className === "el-icon-check") {
        var element = document.getElementsByClassName("el-image-viewer__img");
        let oldImgSrc = (element[0].src || "").replace(window.origin, "")
        let index = this.viewList.findIndex(i => i == oldImgSrc)
        if(index != -1) {
          messageC("图片保存中...")
          (element[0]).then((canvas) => {
            let img = canvas.toDataURL("image/png")
            _this.fileList.splice(index, 1, img)
            _this.base64ToFile(img.split(',')[1], index)
            messageC("图片保存成功！")
          });
        }
      }
    },
  },

  watch: {
    '$attrs.show'(nval, oval) {
      if(nval == true) {
        setTimeout(() => this.initCamera(), 100)
      }
    }
  }
}
</script>
<style lang='scss'>
</style>